import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;

public class aMF_bookfind_manager_findbookbyid extends JFrame {
    private JTextField timeSearchField;
    private JButton searchButton;
    private JTable table;
    private DefaultTableModel tableModel;


    public aMF_bookfind_manager_findbookbyid() {
        setTitle("Book Management");
        setSize(800, 400);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLayout(new BorderLayout());

        timeSearchField = new JTextField(20);
        searchButton = new JButton("查询");

        JPanel searchPanel = new JPanel();
        searchPanel.add(new JLabel("请输入入库时间查询(如2024):"));
        searchPanel.add(timeSearchField);
        searchPanel.add(searchButton);

        String[] columnNames = {"ID", "书名", "作者", "存储时间", "数量", "位置"};
        tableModel = new DefaultTableModel(columnNames, 0);
        table = new JTable(tableModel);

        add(searchPanel, BorderLayout.NORTH);
        add(new JScrollPane(table), BorderLayout.CENTER);

        searchButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                searchByStorageTime();
            }
        });
    }

    private void searchByStorageTime() {
        String searchTime = timeSearchField.getText().trim();

        String query = "SELECT * FROM book_information WHERE storage_time LIKE ?";
        try (Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javaproject", "root", "root");
             PreparedStatement stmt = conn.prepareStatement(query)) {
            stmt.setString(1, "%" + searchTime + "%");
            ResultSet rs = stmt.executeQuery();

            tableModel.setRowCount(0); // 清空表格
            while (rs.next()) {
                Object[] row = {
                        rs.getString("book_id"),
                        rs.getString("book_title"),
                        rs.getString("writer"),
                        rs.getString("storage_time"),
                        rs.getString("number"),
                        rs.getString("position")
                };
                tableModel.addRow(row);
            }
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(this, "数据库查询失败: " + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
        }
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(() -> new aMF_bookfind_manager_findbookbyid().setVisible(true));
    }
}